package br.com.colegio.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import br.com.colegio.dao.storage.AlunoData;
import br.com.colegio.dao.storage.Storage;
import br.com.colegio.util.SpecialCharFilter;
import br.com.colegio.vo.Aluno;

public class AlunoDAO
{
	public static Collection<Object> list()
	{
		try
		{
			return Storage.select(Aluno.class.getName(), "nome");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return null;
	}

	public static Aluno get(Long cod)
	{
		try
		{
			Object res = Storage.get(Aluno.class.getName(), cod);

			if (res != null)
				return (Aluno)res;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return null;
	}

	public static Collection<Object> getByCodigo(String codigo)
	{
		try
		{
			String params = "String p1";
			String filter = " codigo == p1";

			Map<String, Object> parVal = new HashMap<String, Object>();
			parVal.put("p1", codigo);

			return Storage.select(Aluno.class.getName(), filter, params, parVal, null);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return null;
	}

	public static Collection<Object> selectLike(String s)
	{
		try
		{
			if (s != null)
			{
				Map<String, Object> parVal = new HashMap<String, Object>();
				parVal.put("p1", s.toUpperCase());
				parVal.put("p2", s.toLowerCase());

				Collection<Object> r = Storage.select(Aluno.class.getName(),
									"tituloBrasil.startsWith(p2) || tituloBrasil.startsWith(p1)",
									"String p1, String p2",
									parVal, "nome");

				r.addAll(Storage.select(Aluno.class.getName(),
									"tituloOriginal.startsWith(p2) || tituloOriginal.startsWith(p1)",
									"String p1, String p2",
									parVal, "nome"));
				
				return r;
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return null;
	}

	public static Aluno save(String codigo, String nome, String turma, String grupo) throws Exception
	{
		Aluno a = AlunoData.getInstance().getAluno(codigo);

		if (a == null)
			a = new Aluno();

		a.setCodigo(codigo);
		a.setNome(SpecialCharFilter.replaceSpecial(nome).toUpperCase().trim());
		a.setTurma(turma);
		a.setGrupo(grupo);

		a = (Aluno)Storage.save(a);

		AlunoData.getInstance().atualizaData(a);

		return a;
	}

	public static Aluno save(Aluno reg) throws Exception
	{
		return (Aluno)Storage.save(reg);
	}

	public static void delete(Long reg) throws Exception
	{
		Storage.delete(Aluno.class.getName(), reg);
	}
}
